<template>
  <div class="addtaskpage-wrapper">
    <div class="task-name">
      <span style="color:red; position: absolute; left: 10px;">*</span>
      <img @click="coverDialog = true;" :src="form.taskUrl? 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/livolobim/task/'+form.taskUrl : 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/livolobim/task/icon%20orange-1.png'" alt="">
      <textarea v-model="form.taskName" placeholder="请输入任务名称"></textarea>
    </div>
    <div class="form-item-wrapper">
      <div class="form-label">
        <i class="el-icon-coin"></i>所属{{subTaskInProject || ($route.params.copyTask && form.taskDatatype==='3')? '任务': '项目'}}
      </div>
      <div class="form-input" @click="openModuleSelect" style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
        <span style="color:red; position: absolute; left: 10px;">*</span>
        <span v-if="!subTaskInProject && !$route.params.copyTask" :style="{'color': form.taskBelongName? 'black': '#C0C4CC'}">{{form.taskBelongName? form.taskBelongName: '选择所属项目'}}</span>
        <span v-if="$route.params.copyTask && form.taskDatatype==='2'" :style="{'color': form.taskBelongName? 'black': '#C0C4CC'}">{{form.taskBelongName}}</span>
        <span v-if="$route.params.copyTask && form.taskDatatype==='3'" :style="{'color': form.taskBelongName? 'black': '#C0C4CC'}">{{form.taskBelongName? form.taskBelongName: '选择所属任务'}}</span>
        <span v-if="subTaskInProject" style="color: black;">{{subTaskInProject}}</span>
      </div>
    </div>
    <div class="form-item-wrapper">
      <span style="color:red; position: absolute; left: 10px;">*</span>
      <div class="form-label">
        <i class="el-icon-user"></i>负责人
      </div>
      <div class="form-input" @click="selectDingUsers('principal')">
        <span :style="{'color': dingUserList.principal.name.length > 0? 'black': '#C0C4CC'}">{{dingUserList.principal.name.length > 0? dingUserList.principal.name.join(','): '选择负责人'}}</span>
      </div>
    </div>
    <div class="form-item-wrapper">
      <span style="color:red; position: absolute; left: 10px;">*</span>
      <div class="form-label">
        <i class="el-icon-user"></i>确认人
      </div>
      <div class="form-input" @click="selectDingUsers('confirm')">
        <span :style="{'color': dingUserList.confirm.name.length > 0? 'black': '#C0C4CC'}">{{dingUserList.confirm.name.length > 0? dingUserList.confirm.name.join(','): '选择确认人'}}</span>
      </div>
    </div>
    <div class="form-item-wrapper">
      <span style="color:red; position: absolute; left: 10px;">*</span>
      <div class="form-label">
        <i class="el-icon-date"></i>时间
      </div>
      <div class="form-input">
        <span :style="{'color': form.taskStartTime? 'black': '#C0C4CC'}" @click="selectDate('taskStartTime')">{{form.taskStartTime? form.taskStartTime: '选择开始时间'}}</span><span style="color: black;margin: 0 10px;">-</span><span :style="{'color': form.taskEndTime? 'black': '#C0C4CC'}" @click="selectDate('taskEndTime')">{{form.taskEndTime? form.taskEndTime: '选择截止时间'}}</span>
      </div>
    </div>
    <div class="form-item-wrapper">
      <div class="form-label">
        <i class="el-icon-time"></i>工期
      </div>
      <div class="form-input">
        <span :style="{'color': planTime? 'black': '#C0C4CC'}">
          {{planTime}}天     
        </span>
      </div>
    </div>
    <div class="form-item-wrapper">
      <div class="form-label">
        <i class="el-icon-data-line"></i>任务绩效
      </div>
      <div class="form-input">
        <input type="text" v-model="form.taskPerformanceAppraisal">
      </div>
    </div>
    <div class="form-item-wrapper" style="min-height:50px;height: auto;">
      <div class="form-label" style="width: 37px;">
        <i class="el-icon-edit-outline"></i>
      </div>
      <div class="form-input" @click="showInfo = true;" style="width: calc(100% - 37px)">
        <span v-if="!form.taskInfo && form.taskAttachment.length === 0">添加描述和附件</span>
        <div v-if="form.taskInfo || form.taskAttachment.length > 0" style="line-height: 32px;padding:8px;">
          <span style="color: black;word-break:break-all;">{{form.taskInfo}}</span>
          <div class="fileitem" v-for="(file, idx) in form.taskAttachment" :key="idx">
            <img style="width:16px;height:16px;position:relative;top:-2px;margin-right:2px;" :src="getPic(file.name)" alt="">
            <span style="width: 90%;overflow:hidden;text-overflow: ellipsis;vertical-align:bottom;white-space:nowrap;display:inline-block;" @click.stop="downloadFile(file.url, file.name)">{{file.name}}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="form-item-wrapper">
      <div class="form-label">
        <i class="el-icon-star-off"></i>关注人
      </div>
      <div class="form-input" @click="selectDingUsers('cc', 300)" style="overflow: hidden;">
        <span style="display: inline-block;width: 100%;overflow: hidden;white-space: nowrap;" :style="{'color': dingUserList.cc.name.length > 0? 'black': '#C0C4CC'}">{{dingUserList.cc.name.length > 0? dingUserList.cc.name.join(','): '选择关注人'}}</span>
      </div>
    </div>
    <div class="action-bar">
      <div @click="goBack">取消</div>
      <div @click="submitForm">确定</div>
    </div>
    <div class="select-page" v-if="showModule">
      <div class="mask" @click="showModule = false;"></div>
      <div class="module-panel">
        <div class="title">{{form.taskDatatype==='3' ? '任务' : '项目'}}列表</div>
        <div class="module-wrapper">
          <div v-for="moduleItem in projectList" :key="moduleItem.id" class="module-item">
            <el-radio v-model="form.taskBelongId" :label="moduleItem.id">{{moduleItem.taskName}}</el-radio>
          </div>
        </div>
        <div class="bottom-btn">
          <div @click="showModule = false;">取消</div>
          <div @click="selectProject">确定</div>
        </div>
      </div>
    </div>
    <div class="info-page" v-if="showInfo">
      <div class="task-info">
        <div class="mobile-input-wp">
          <el-input style="width: 100%;" autofocus="true" placeholder="请输入任务描述" @input="detectInput" rows="8" v-model="form.taskInfo" type="textarea"></el-input>
        </div>
      </div>
      <div class="upload-file">
        <input ref="uploadInput" style="display:none;" type="file" @change="uploadFile($event)" multiple>
        <div class="upload-btn" @click="$refs.uploadInput.click()">添加附件</div>
        <div class="fileitem" v-for="(file, idx) in form.taskAttachment" :key="idx">
          <img style="width:16px;height:16px;position:relative;top:-2px;margin-right:2px;" :src="getPic(file.name)" alt="">
          <span @click.stop="downloadFile(file.url, file.name)" style="width: 60%;overflow:hidden;text-overflow: ellipsis;vertical-align:bottom;white-space:nowrap;display:inline-block;">{{file.name}}</span>
          <span class="uploadtip" v-if="file.url" @click="delFile(idx)"><i class="el-icon-delete"></i></span>
          <span class="uploadtip" style="color: red;cursor:none;" v-if="!file.url">上传中<i class="el-icon-loading"></i></span>
        </div>
      </div>
      <div class="bottom-btn">
        <div @click="showInfo = false;">取消</div>
        <div @click="showInfo = false;">确定</div>
      </div>
    </div>
    <el-dialog title="选择图片" :visible.sync="coverDialog"  width="80%" :append-to-body="true">
      <div class="cover-wrapper">
        <div v-for="cover in 15" :key="cover">
          <img @click="selectCover('icon%20blue-' + cover + '.png')" :src="'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/livolobim/task/icon%20blue-' + cover + '.png'" style="width: 40px; height: 40px;display:block;border-radius: 3px;">
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dingMixin from "@/mixins/ding";
import formUtil from "@/utils/formUtil";
import {dateUtil} from '@/utils/dateUtil'

export default {
  data() {
    return {
      showInfo: false,
      showModule: false,
      visible: false,
      projectList: [],
      dingUserList: {
        principal: { id: [], img: [], name: [] },
        confirm: { id: [], img: [], name: [] },
        cc: { id: [], img: [], name: [] }
      },
      planTime: 0,
      taskTime: [],
      fileList: [],
      form: {
        taskName: "",
        taskInfo: "",
        taskBelongId: "",
        taskBelongName: "",
        taskPrincipalId: "",
        principalAvatar: "",
        taskPrincipalName: "",
        taskConfirmId: "",
        confirmAvatar: "",
        taskConfirmName: "",
        taskStartTime: "",
        taskEndTime: "",
        taskCcId: "",
        ccAvatar: "",
        taskCcName: "",
        taskPerformanceAppraisal: 0,
        taskStatus: 0,
        taskAttachment: [],
        taskDatatype: '2',
        taskUrl: 'icon%20blue-1.png'
      },
      coverDialog: false,
      subTaskInProject: '',
    };
  },
  mixins: [dingMixin],
  async mounted() {
    if(this.$route.params.copyTask) {
      this.form = this.$route.params.data
      if(this.form.taskDatatype === '3') {
        this.getTaskListUnderProject(this.form.taskBelongId);
        this.form.taskBelongId = '';
        this.form.taskBelongName = '';
      }
      if (this.form.taskPrincipalId !== '') this.dingUserList.principal.id = this.form.taskPrincipalId.split(',');
      if (this.form.taskPrincipalName !== '') this.dingUserList.principal.name = this.form.taskPrincipalName.split(',');
      if (this.form.taskConfirmId !== '') this.dingUserList.confirm.id = this.form.taskConfirmId.split(',');
      if (this.form.taskConfirmName !== '') this.dingUserList.confirm.name = this.form.taskConfirmName.split(',');
      if (this.form.taskCcId !== '')  this.dingUserList.cc.id = this.form.taskCcId.split(',');
      if (this.form.taskCcName !== '')  this.dingUserList.cc.name = this.form.taskCcName.split(',');
      this.planTime = parseInt((new Date(this.form.taskEndTime) - new Date(this.form.taskStartTime)) / 1000 / 60 / 60 / 24) + 1;
    } else {
      let taskName = this.$route.params.taskName;
      if(taskName) {
        this.form.taskBelongId = this.$route.params.id;
        this.form.taskBelongName = this.$route.params.taskName;
        this.subTaskInProject = this.$route.params.projectName + ' - ' + this.$route.params.taskName;
        this.form.taskDatatype = '3';
      }else if(this.$route.params.projectId) {
        this.form.taskBelongId = this.$route.params.projectId;
        this.form.taskBelongName = this.$route.params.projectName;
      } else {
        this.projectList = await this.$httpN.postB("division/task/getVisibleProjectList", {taskStatus: '1'});
      }
    }
  },
  methods: {
    detectInput() {
      if(this.form.taskInfo.charAt(this.form.taskInfo.length - 1) === '@'){
        this.complexPicker(1).then((data)=>{
          this.form.taskInfo += data[0].name + ' '
        })
      }
    },
    openModuleSelect() {
      if(((!this.subTaskInProject && !this.$route.params.copyTask) || (this.$route.params.copyTask && this.form.taskDatatype==='3')) && (!this.$route.params.projectId)) this.showModule = true; 
    },
    downloadFile: function (url, fileName) {//跨域文件路径、下载到本地的文件名
      if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(url)) {
         return this.dingPreviewPic(url);
      }else{
        this.mobileAlert('手机不支持下载文件，请到电脑端下载');
      }
    },
    selectProject() {
      this.showModule = false;
      this.projectList.forEach(item => {
        if (item.id === this.form.taskBelongId) {
          this.form.taskBelongName = item.taskName;
        }
      });
    },
    selectDate(type) {
      this.mobileSelectDate(this.currentDate, (date) => {
        this.form[type] = date;
        if(this.form.taskStartTime && this.form.taskEndTime && (new Date(this.form.taskStartTime) - new Date(this.form.taskEndTime) > 0) ) {
          this.form[type] = ''
          return this.mobileAlert('截止日期不可小于开始日期')
        }
        this.changePlanTime();
      });
    },
    changePlanTime(e) {
      let startTime = new Date(this.form.taskStartTime);
      let endTime = new Date(this.form.taskEndTime);
      this.planTime = parseInt((endTime - startTime) / 1000 / 60 / 60 / 24) + 1;
    },
    selectDingUsers(showName, number = 1) {
      this.complexPicker(number, [], this.dingUserList[showName].id).then(
        data => {
          this.dingUserList[showName].id = [];
          this.dingUserList[showName].img = [];
          this.dingUserList[showName].name = [];
          data.forEach((item, idx) => {
            this.dingUserList[showName].id.push(item.emplId);
            this.dingUserList[showName].img.push(item.avatar);
            this.dingUserList[showName].name.push(item.name);
          });
        }
      );
    },
    async submitForm() {
      this.projectList.forEach(item => {
        if (item.id === this.form.taskBelongId) {
          this.form.taskBelongName = item.taskName;
          return false;
        }
      });
      this.form.taskPrincipalId = this.dingUserList.principal.id.join(",");
      this.form.principalAvatar = this.dingUserList.principal.img.join(",");
      this.form.taskPrincipalName = this.dingUserList.principal.name.join(",");
      this.form.taskConfirmId = this.dingUserList.confirm.id.join(",");
      this.form.confirmAvatar = this.dingUserList.confirm.img.join(",");
      this.form.taskConfirmName = this.dingUserList.confirm.name.join(",");
      this.form.taskCcId = this.dingUserList.cc.id.join(",");
      this.form.ccAvatar = this.dingUserList.cc.img.join(",");
      this.form.taskCcName = this.dingUserList.cc.name.join(",");
      this.form.taskManageId = this.userInfo.dingId;
      this.form.taskManageName = this.userInfo.realName;

      if(!this.form.taskBelongId) return this.mobileAlert('请选择所属项目')
      if(!this.form.taskName) return this.mobileAlert('请输入任务名称')
      if(this.form.taskName.length > 30) return this.mobileAlert('任务名称不要超过30个字')
      if(!this.form.taskPrincipalId) return this.mobileAlert('请选择任务负责人')
      if(!this.form.taskConfirmId) return this.mobileAlert('请选择任务确认人')
      if(!this.form.taskStartTime) return this.mobileAlert('请选择任务开始时间')
      if(!this.form.taskEndTime) return this.mobileAlert('请选择任务结束时间')
      if(!this.form.taskPrincipalId) return this.mobileAlert('请选择任务负责人')
      if(!this.form.taskPrincipalId) return this.mobileAlert('请选择任务负责人')
      if(isNaN(this.form.taskPerformanceAppraisal)) return this.mobileAlert('任务绩效为数字')
      if(this.form.taskPerformanceAppraisal < 0) return this.mobileAlert('任务绩效大于0')
      if(this.form.taskAttachment.filter(item => !item.url).length > 0) return this.mobileAlert('附件正在上传，请稍候……');

      if (!this.form.taskStatus) this.form.taskStatus = 1;
      if (!(await this.$httpN.postB("division/task/projectOrTaskSave", this.form))) return;
      this.mobileMessage('保存成功')
      window.NEEDREFRESH = true;
      this.$router.go(-1);
    },
    async uploadFile(e) {
      var files = e.target.files;
      var $this = this;
      Object.keys(files).forEach(function(key){
        var file = files[key];
        if(file.size / 1024 / 1024 > 20) return $this.mobileAlert('上传单个文件大小不能超过20MB!请压缩文件')
        var formData = new FormData();
        formData.append("file", file);
        formData.append("name", 'file');
        let newfile = {
          name: file.name,
          url: '',
          size: file.size,
          uploader: $this.userInfo.realName,
          time: dateUtil.thisDay()
        }
        $this.form.taskAttachment.push(newfile)
        $this.$httpN.upload('fileUpload', formData).then(res => {
          if(res.data.code === 0) {
            newfile.url = res.data.url;;
          }else if(res.data.code === 500) {
            $this.form.taskAttachment.pop();
          }
        })
      })
      e.target.value = '';
    },
    delFile(idx){
      this.form.taskAttachment.splice(idx, 1)
    },
    openCoverChange() {
      this.coverDialog = true;
    },
    selectCover(img) {
      this.coverDialog = false;
      this.form.taskUrl = img
    },
    goBack() {
      this.$router.go(-1);
    },
    getPic(filename) {
      if(filename) {
        if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438103037435905.png'
        }else if(/\.(txt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438530785140737.png'
        }else if(/\.(xls|xlsx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438725690253314.png'
        }else if(/\.(doc|docx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439195636850689.png'
        }else if(/\.(psd)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439984203751426.png'
        }else if(/\.(pdf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440139145535490.png'
        }else if(/\.(ppt|pptx|dps|dpt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440657859305473.png'
        }else if(/\.(rar|zip|arj|gz)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442063039193090.png'
        }else if(/\.(html|htm)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442135319633921.png'
        }else if(/\.(dwg|bak|dwt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276441741667459074.png'
        }else if(/\.(wav|aif|au|mp3|ram|wma|mmf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442006684524546.png'
        }else if(/\.(avi|mov|rmvb|rm|flv|mp4)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442233483124737.png'
        }else{
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
        }
      }else {
        return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
      }
    },
    async getTaskListUnderProject(taskId) {
      let taskInfo = await this.$httpN.postB('division/task/taskInfo', {id:taskId})
      let list = await this.$httpN.postB('division/task/getUnCompleteTask', {id: taskInfo.taskBelongId})
      this.projectList = list.filter(item => {  //实际为任务列表
        return item.taskDatatype === '2' && item.taskStatus === '1'
      })
    },
  }
};
</script>

<style lang="scss" scoped>
  input::-webkit-input-placeholder, textarea::-webkit-input-placeholder {
    color: #C0C4CC;
  }

  input:-moz-placeholder, textarea:-moz-placeholder {
    color: #C0C4CC;
  }

  input::-moz-placeholder, textarea::-moz-placeholder {
    color: #C0C4CC;
  }

  input:-ms-input-placeholder, textarea:-ms-input-placeholder {
    color: #C0C4CC;
  }
  .addtaskpage-wrapper{
    min-height: 100vh;
    padding: 16px;
    background: white;
    position: relative;
    .task-name{
      position: relative;
      height: 90px;
      border-bottom: 1px solid #e7e5e5;
      padding-left: 105px;
      padding-top: 5px;
      img{
        width: 70px;
        height: 70px;
        border-radius: 3px;
        position: absolute;
        top:5px;
        left:20px;
      }
      textarea{
        width: 100%;
        height: 80px;
        border: none;
        outline: none;
        resize:none;
      }
    }
    .form-item-wrapper{
      height: 50px;
      border-bottom: 1px solid #e7e5e5;
      line-height: 50px;
      display: flex;
      position: relative;
      .form-label{
        width: 110px;
        color: #909399;
        padding-left: 20px;
        i{
          margin-right: 3px;
        }
      }
      .form-input{
        color: #C0C4CC;
        flex: 1;
        input{
          width: 100%;
          height: 90%;
          border: 0;
          outline: none;
        }
      }
      .fileitem{
        line-height: 32px;
        margin-bottom: 5px;
        background: #F5F5F5;
        padding-left:10px;
        font-size: 12px;
        color: #606266;
        .uploadtip{
          float:right;
          margin-right: 20px;
          cursor: pointer;
        }
      }
    }
    .action-bar{
      position: absolute;
      line-height: 50px;
      width: 100%;
      bottom: 0;
      left: 0;
      display:flex;
      text-align: center;
      div{
        flex:1;
        font-size: 16px;
      }
      >div:first-child{
        background: #F2F2F2;
        color: #909399;
      }
      >div:last-child{
        color: white;
        background: #639efc;
      }
    }
  }
  .select-page{
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 10;
    .mask{
      background: rgba(0,0,0,0.5);
      height: 100%;
      position: absolute;
      top:0;
      left:0;
      width: 100%;
    }
    .module-panel{
      width: 80%;
      position: absolute;
      top:0;
      right: 0;
      height: 100%;
      background: white;
      .title{
        font-weight: bold;
        padding-left: 16px;
        border-bottom: 1px solid #F6F6F6;
        line-height: 46px;
      }
      .module-wrapper{
        height: calc(100vh - 100px);
        overflow: auto;
        padding: 16px 16px;
        height: calc(100% - 100px);
        overflow-y: auto;
        .module-item{
          padding-left:15px;
          line-height: 30px;
          border-bottom: 1px solid #F6F6F6;
          margin-bottom: 5px;
        }
      }
      .bottom-btn{
        position: absolute;
        bottom: 0;
        right:0;
        width: 100%;
        display: flex;
        z-index: 2;
        div{
          flex:1;
          text-align: center;
          line-height: 50px;
          background: #F2F2F2;
          color: #8D8F96;
        }
        >div:last-child{
          color:white;
          background: #639EFC;
        }
      }
    }
  }
  .info-page{
    height: 100vh;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 10;
    background: white;
    padding: 16px;
    .bottom-btn{
      position: absolute;
      bottom: 0;
      right:0;
      width: 100%;
      display: flex;
      div{
        flex:1;
        text-align: center;
        line-height: 50px;
        background: #F2F2F2;
        color: #8D8F96;
      }
      >div:last-child{
        color:white;
        background: #639EFC;
      }
    }
    .task-info{
      textarea{
        width: 100%;
        height: 250px;
        border: none;
        outline: none;
        resize:none;
        background: #F9F9F9;
        padding: 10px;
      }
    }
    .upload-file{
      margin-top: 30px;
      font-size: 14px;
      color: #409EFF;
      .upload-btn{
        color: #409EFF;
        margin-bottom: 10px;
      }
    }
    .fileitem{
      line-height: 32px;
      margin-bottom: 5px;
      background: #F5F5F5;
      padding-left:10px;
      font-size: 12px;
      color: #606266;
      .uploadtip{
        float:right;
        margin-right: 20px;
        cursor: pointer;
      }
    }
  }
  .cover-wrapper{
    display: flex;
    flex-wrap: wrap;
    div{
      height: 40px;
      width: 40px;
      background: #409EFF;
      color: white;
      line-height: 40px;
      text-align: center;
      font-size: 40px;
      position: relative;
      border-radius: 5px;
      margin: 5px;
    }
  }
</style>